const http = require("http");
const ejs = require("ejs");
const app = require("../08 nodejs router/module/moduleExpress");
const mongoClient = require("./module/moduleMongodb");

//通过http.createServer执行了app方法，触发执行了invokeMethod的注册方法
http.createServer(app).listen(8080);

//数据插入
app._get("/add", (req, res) => {
    let insertData = [
        {"name": "haha", "age": 23},
        {"name": "hehe", "age": 28, "sex": "男"}
    ];
    mongoClient.insertDocuments("student", insertData, r => {
        res.send("Inserted " + r.insertedCount + " documents into the collection");
    });
});

//数据删除
app._get("/del", (req, res) => {
    let condition = {
        $or: [
            {"name": "haha"},
            {"name": "hehe"}
        ]
    };
    mongoClient.deleteDocuments("student", condition, r => {
        res.send("Deleted " + r.deletedCount + " documents into the collection");
    });
});

//数据修改
app._get("/edit", (req, res) => {
    let condition = {
        $or: [
            {"name": "haha2"},
            {"name": "hehe2"}
        ]
    };
    let editData = {
        $set: {"name": "haha+hehe"}
    };
    mongoClient.updateDocuments("student", condition, editData, r => {
        res.send("Updated " + r.modifiedCount + " documents into the collection");
    });
});

//数据查询
app._get("/get", function(req, res) {
    let condition = {
        $or: [
            {"name": /haha/},
            {"name": /hehe/}
        ]
    };
    let sort = {"age": -1};
    mongoClient.findDocuments("student", condition, sort, 0, 0, r => {
        // console.log(r);
        ejs.renderFile("./views/student.html", {stList: r}, (err, data) => {
            res.send(data);
        });
    });
});